<template>
  <div class="AddOrUpdate_main add_container column_two">
    <div class="main_main">
      <div class="tab_container">
        <el-tabs v-model="activeName">
          <el-tab-pane label="统计设置" name="first">
            <div class="largeScreenSetting_container">
              <div class="largeScreenSetting_container_main">
                <div class="largeScreenSetting_container_main_left">
                  <div v-for="(item1,index1) in statisticalDataAll" :key="index1" class="left_item_header">
                    <div class="largeScreenSetting_container_header">
                      {{ item1.name }}
                    </div>
                    <a v-for="(item,index) in item1.children.filter(iitem=>!statisticalData.find(iitem2=>iitem2.name==iitem.name))" :key="index" class="left_item" @click="leftClick(item)">
                      <div class="left_item_name">{{ item.name }}</div>
                    </a>
                  </div>
                </div>
                <div class="largeScreenSetting_container_main_middle">
                  <div class="largeScreenSetting_container_main_middle_container">
                    <svg-icon icon-class="大于" />
                  </div>
                </div>
                <div class="largeScreenSetting_container_main_right">
                  <div class="right_item_header">
                    <div class="right_item_header_left">展示模块</div>
                    <div class="right_item_header_right">排序</div>

                  </div>
                  <div ref="scrollRef" class="right_item_container">

                    <div v-for="(item,index) in statisticalData" :key="index" class="right_item">
                      <div class="right_item_left">
                        <div class="right_item_left_left">
                          <div class="right_item_left_index">&nbsp;{{ index+1 }}&nbsp;</div>
                          <div class="right_item_left_name">{{ item.name }}</div>
                        </div>
                        <div class="right_item_left_right">
                          <a class="right_item_left_draggable"><svg-icon icon-class="行拖动" /></a>
                          <a class="right_item_left_delete" @click="removeRow1(index)"><svg-icon icon-class="行删除" /></a>
                        </div>
                      </div>
                    </div>

                  </div>

                  <!-- <div class="right_item_footer">* 最多只能选6项</div> -->
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="图表设置" name="second">

            <div class="largeScreenSetting_container largeScreenSetting_chart">
              <div class="largeScreenSetting_container_main">
                <div class="largeScreenSetting_container_main_left">
                  <div v-for="(item1,index1) in chartDataAll" :key="index1" class="left_item_header">
                    <div class="largeScreenSetting_container_header">
                      {{ item1.name }}
                    </div>
                    <a v-for="(item,index) in item1.children.filter(iitem=>!chartData.find(iitem2=>iitem2.name==iitem.name))" :key="index" class="left_item" @click="rightClick(item)">
                      <div class="left_item_name">{{ item.name }}</div>
                    </a>
                  </div>
                </div>
                <div class="largeScreenSetting_container_main_middle">
                  <div class="largeScreenSetting_container_main_middle_container">
                    <svg-icon icon-class="大于" />
                  </div>
                </div>
                <div class="largeScreenSetting_container_main_right">
                  <div class="right_item_header">
                    <div class="right_item_header_left">展示模块</div>
                    <div class="right_item_header_middle">自定义配置</div>
                    <div class="right_item_header_right">排序</div>

                  </div>
                  <div ref="scrollRef2" class="right_item_container right_item_container_forDrop">

                    <div v-for="(item,index) in chartData" :key="index" class="right_item">
                      <div class="right_item_left">
                        <div class="right_item_left_left">
                          <!--                          <div class="right_item_left_index">&nbsp;{{ index+1 }}&nbsp;</div>-->
                          <div class="right_item_left_name">{{ item.name }}</div>
                        </div>
                        <div class="right_item_left_middle">

                          <div v-if="'number' in item" class="customization">
                            <div class="customization_name">
                              目标值：
                            </div>
                            <div class="customization_value">
                              <el-input
                                v-model="item.number"
                                placeholder="请输入"
                                type="number"
                                @input="haveTwoDecimalPlaces($event,index)"
                              />
                            </div>
                          </div>

                          <div v-if="'threshold' in item" class="customization">
                            <div class="customization_name">
                              阈值：
                            </div>
                            <div class="customization_value">
                              <el-input
                                v-model="item.threshold"
                                placeholder="请输入"
                                type="number"
                              />
                            </div>
                          </div>
                          <div v-else-if="'notice' in item" class="customization">
                            <div class="customization_name">
                              预警值：超过
                            </div>
                            <div class="customization_value">
                              <el-input
                                v-model="item.notice"
                                placeholder="请输入"
                                type="number"
                              />
                            </div>
                            <div class="customization_name">
                              小时
                            </div>
                          </div>
                          <div v-if="'deviceIds' in item" class="customization">
                            <div class="customization_name">
                              设备：
                            </div>
                            <div class="customization_value">
                              <!--                              <el-select-->
                              <!--                                v-model="item.deviceIds"-->
                              <!--                                multiple-->
                              <!--                                collapse-tags-->
                              <!--                                :multiple-limit="4"-->
                              <!--                                placeholder="请选择"-->
                              <!--                              >-->
                              <!--                                <el-option-->
                              <!--                                  v-for="item in deviceOptions"-->
                              <!--                                  :key="item.companyDeviceId"-->
                              <!--                                  :label="item.iotType+':'+item.deviceName"-->
                              <!--                                  :value="item.companyDeviceId"-->
                              <!--                                />-->
                              <!--                              </el-select>-->

                              <!--   自定义多选组件    -->
                              <JLINKSelectMultiple
                                v-model="item.deviceIds"
                                :select-options="deviceOptions"
                                :multiple-limit="4"
                              />

                            </div>
                          </div>
                        </div>
                        <div class="right_item_left_right">
                          <a class="right_item_left_draggable"><svg-icon icon-class="行拖动" /></a>
                          <a class="right_item_left_delete" @click="removeRow2(index)"><svg-icon icon-class="行删除" /></a>
                        </div>
                      </div>
                    </div>

                  </div>

                  <!-- <div class="right_item_footer">* 最多只能选6个，其中销售发货预警/采购交期预警/出入库通知/任务统计算2个</div> -->
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <div class="main_bottom">
      <el-button @click.stop="backDefault">恢复默认</el-button>
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { savePageSettings, backDefault } from '@/api/common/common'
import Sortable from 'sortablejs'
import { mapGetters } from 'vuex'
import { realStatusList as getDeviceOptions } from '@/api/superManage/iotManage/iotConfiguration'
export default {
  name: 'AddOrUpdate',
  computed: {
    ...mapGetters([
      'companyId'
    ])
  },
  props: {
    layerid: {},
    settingData: {}
  },
  data() {
    return {
      pageData: {
        isAll: 0,
        // iotType: '电表',
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      activeName: 'first',
      statisticalDataAll: [ // 所有可选的统计数据项
        {
          name: '销售看板',
          children: [
            { name: '未完成销售订单', icon: '未完成销售订单', dataKey: 'unFinishSaleOrderSum', bgColor: '#C9EEFF4D', isShow: true },
            { name: '待发货单', icon: '发货单', dataKey: 'willDeliverSum', bgColor: '#FFEBC94D', isShow: true },
            { name: '本月销售退货单', icon: '退货单', dataKey: 'returnSum', bgColor: '#C9EEFF4D', isShow: true },
            { name: '本月销售逾期订单', icon: '逾期订单', dataKey: 'overdueSum', bgColor: '#FFC9C94D', isShow: true }
          ]
        }
        // {
        //   name: '采购看板',
        //   children: [
        //     { name: '本月采购订单', icon: '本月采购订单', dataKey: 'purchaseOrderNum', bgColor: '#C9EEFF4D',isShow:true },
        //     { name: '本月采购逾期订单', icon: '采购逾期工单', dataKey: 'overduePurchaseOrderNum', bgColor: '#FFC9C94D',isShow:true },
        //     { name: '本月采购退货单', icon: '采购退货工单', dataKey: 'returnPurchaseOrderNum', bgColor: '#C9EEFF4D',isShow:true },
        //     { name: '来料待检验', icon: '来料待检验单', dataKey: 'inspectPurseOrderNum', bgColor: '#FFEBC94D',isShow:true }
        //   ]
        // },
        // {
        //   name: '仓库看板',
        //   children: [
        //     { name: '物料总数', icon: '物料总数', dataKey: 'materialCount', bgColor: 'rgba(201, 238, 255,.3)', isShow: true },
        //     { name: '待入库单', icon: '待入库单', dataKey: 'waitIn', bgColor: 'rgba(255, 235, 201,.3)', isShow: true },
        //     { name: '待出库单', icon: '待出库单', dataKey: 'waitOut', bgColor: 'rgba(255, 235, 201,.3)', isShow: true },
        //     { name: '待盘点单', icon: '待盘点单', dataKey: 'waitCheck', bgColor: 'rgba(255, 235, 201,.3)', isShow: true },
        //     { name: '超储物料数量', icon: '超储物料数量', dataKey: 'overStorage', bgColor: 'rgba(255, 201, 201,.3)', isShow: true },
        //     { name: '低储物料数量', icon: '低储物料数量', dataKey: 'lowStorage', bgColor: 'rgba(201, 255, 225,.3)', isShow: true }
        //   ]
        // },

      ],
      statisticalData: [], // 右边要展示的统计数据项
      chartDataAll: // 所有可选的图表数据项
        [
          {
            name: '销售看板',
            children: [
              { name: '物料销售排行', component: 'MaterialSalesRanking', isShow: true },
              { name: '发货及时率', component: 'TimelyDeliveryRate', number: 60, isShow: true },
              { name: '销售发货预警', component: 'saleSendWarning', length: '2', isShow: true }
            ]
          }
          // {
          //   name: '采购看板',
          //   children: [
          //     { name: '物料采购排行', component: 'materialPurchaseSort' },
          //     { name: '交货及时率', component: 'consignmentTimely', number: 60 },
          //     { name: '采购交期预警', component: 'purchaseDeliveryTimeWarning', length: '2' }
          //   ]
          // },
          // {
          //   name: '仓库看板',
          //   children: [
          //     { name: '仓库库存占比', component: 'WarehouseInventoryProportion' },
          //     { name: '物料分类库存占比', component: 'MaterialClassificationInventory' },
          //     { name: '超储物料明细', component: 'OverstockedMaterials' },
          //     { name: '低储物料明细', component: 'LowstockedMaterials' },
          //     { name: '出入库通知', component: 'InboundOutboundNotifications', length: 2, notice: 24 }
          //   ]
          // },

        ],
      chartData: [], // 右边要展示的图表数据项
      doubleLengthCharts: ['销售发货预警', '采购交期预警', '出入库通知', '任务统计'] // 图表中这些占 2 个位置
    }
  },
  mounted() {
    // console.log(this.settingData)
    // this.statisticalDataAll.forEach(ele =>{
    //   ele.children.
    // })
    console.log(this.settingData)
    this.statisticalData = this.$deepClone(this.settingData.StatisticsItem.filter(item => item.isShow))
    this.chartData = this.$deepClone(this.settingData.ChartItem.filter(item => item.isShow))
    this.$nextTick(() => {
      this.rowDrop()
      this.rowDrop2()
    })
  },
  methods: {
    backDefault() {
      backDefault({ userId: this.$store.state.user.userId, pageId: this.$parent.pageId }).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        // this.$layer.close(this.layerid) // 关闭弹框
        // this.$parent.getPageSettings() // 调用父组件的方法

        location.reload() // 直接刷新页面吧
      })
    },
    onSubmit() {
      if (this.statisticalData.length == 0) {
        this.$message.warning('统计设置至少保留一项')
        return
      }
      if (this.chartData.length == 0) {
        this.$message.warning('图表设置至少保留一项')
        return
      }
      const submitData = {}
      submitData.json = JSON.stringify({ StatisticsItem: this.statisticalData, ChartItem: this.chartData })
      submitData.id = this.settingData.id
      submitData.userId = this.$store.state.user.userId
      submitData.pageId = this.settingData.pageId
      // submitData.json = JSON.stringify(this.settingDatas)
      savePageSettings(submitData).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.$layer.close(this.layerid) // 关闭弹框
        this.$parent.getPageSettings() // 调用父组件的方法
        setTimeout(() => {
          location.reload() // 直接刷新页面吧
        }, 1000)
      })
    },
    leftClick(data) {
      if (this.statisticalData.length == 6) {
        this.$message.warning('最多展示 6 项统计数据')
      } else {
        this.statisticalData.push(data)
      }
    },
    rightClick(data) {
      this.chartData.push(data)
    },
    removeRow1(index) {
      const cacheTableData = this.$deepClone(this.statisticalData)
      this.statisticalData = []
      cacheTableData.splice(index, 1)
      setTimeout(() => {
        this.statisticalData = cacheTableData
      }, 1)
    },
    removeRow2(index) {
      const cacheTableData = this.$deepClone(this.chartData)
      this.chartData = []
      cacheTableData.splice(index, 1)
      setTimeout(() => {
        this.chartData = cacheTableData
      }, 1)
    },
    setFileName2(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    getDeviceOptions() {
      getDeviceOptions(this.pageData).then(res => {
        this.deviceOptions = res.data
        this.deviceOptions.forEach(item => {
          item.value = item.companyDeviceId
          item.label = item.iotType + ':' + item.deviceName
        })
        console.log('this.deviceOptions ', this.deviceOptions)
      })
    },
    // 保留两位小数
    haveTwoDecimalPlaces(e, index) {
      if (e.indexOf('.') > -1) {
        const afterPoint = e.split('.')
        if (e !== 0 && afterPoint[1].length > 2) {
          this.chartData[index].number = e.slice(0, e.indexOf('.') + 3)
          this.$message.warning('至多可输入两位小数')
        } else if (e == 0) {
          this.chartData[index].number = 0
        }
      } else {
        this.chartData[index].number = e
      }
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        console.log('JSON.parse(res.data.statistical)', JSON.parse(res.data.statistical))

        this.statisticalData = JSON.parse(res.data.statistical).filter(item => item.isShow != '0')
        this.chartData = JSON.parse(res.data.chart).filter(item => item.isShow != '0')
        console.log(this.statisticalData)
        console.log(this.chartData)
      })
    },
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.right_item_container')
      const _this = this
      Sortable.create(tbody, {
        handle: '.right_item_left_draggable',
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.statisticalData[oldIndex])
          const cacheTableData = _this.$deepClone(_this.statisticalData)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.statisticalData = []
          const cacheScroll = _this.$refs.scrollRef.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.statisticalData = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },
    rowDrop2() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.right_item_container_forDrop')
      const _this = this
      Sortable.create(tbody, {
        handle: '.right_item_left_draggable',
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.chartData[oldIndex])
          const cacheTableData = _this.$deepClone(_this.chartData)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.chartData = []
          const cacheScroll = _this.$refs.scrollRef2.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.chartData = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef2.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },

    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.tab_container{
  margin-top: -15px;
}
.largeScreenSetting_container{
  margin: 0 20px;
  .largeScreenSetting_container_header{
    height: 35px;
   color: #333333;
    display: flex;align-items: center;
    margin-top: 10px;padding-left: 20px;font-weight: bold;
  }
  .largeScreenSetting_container_main{
    display: flex;
    .largeScreenSetting_container_main_left{
      width: 300px;
      height:500px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0 20px 10px 20px;
      overflow-y: auto;
      .left_item{
        margin-top: 10px;
        height: 30px;
        border-radius: 15px;
        background: #EBF2FF;
        padding: 0 20px;
        display: flex;align-items: center;
        font-size: 14px;color: #333333;
        .left_item_name{
          overflow:hidden; //超出的文本隐藏
          text-overflow:ellipsis; //溢出用省略号显示
          white-space:nowrap; //溢出不换行
          width: 210px;
        }
      }
      .left_item:hover{
        background-color:  rgba(56, 123, 252, 0.5);
        color: white;
      }
    }
    .largeScreenSetting_container_main_middle{
      //flex: 1;
      width: 120px;
      display: flex;justify-content: center;align-items: center;
      .largeScreenSetting_container_main_middle_container{
        width: 80px;
        height: 50px;
        border-radius: 6px;
        background: #6095FD;
        display: flex;justify-content: center;align-items: center;
        font-size: 20px;
      }
    }
    .largeScreenSetting_container_main_right{
      width: 350px;
      height: 500px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0 0 10px 20px;
      position: relative;
      .right_item_header{
        height: 35px;display: flex;align-items: center;
        margin-top: 10px;font-weight: bold;
        justify-content: space-between;
        .right_item_header_left{
          padding-left: 39px;
        }
        .right_item_header_right{
          width: 90px;
        }
      }

      .right_item_container{
        overflow-y: auto;
        height: calc(100% - 55px);

      }
      .right_item{
        margin-top: 10px;margin-right: 20px;
        height: 30px;
        display: flex;align-items: center;
        font-size: 14px;color: #333333;
        .right_item_left{
          border-radius: 15px;
          background: #EBF2FF;
          height: 100%;
          flex: 1;
          display: flex;align-items: center;
          justify-content: space-between;
          .right_item_left_left{
            display: flex;align-items: center;
            .right_item_left_index{
              width: 20px;height: 20px;border-radius: 15px;
              margin-left: 5px;background: #BACBEC;
              display: flex;justify-content: center;align-items: center;
            }
            .right_item_left_name{
              width: 160px;
              font-size: 14px;color: #333333;
              padding-left: 15px;
              overflow:hidden; //超出的文本隐藏
              text-overflow:ellipsis; //溢出用省略号显示
              white-space:nowrap; //溢出不换行
            }
          }
          .right_item_left_right{
            display: flex;align-items: center;
            .right_item_left_draggable{
              font-size: 16px;
              margin-right: 20px;
            }
            .right_item_left_delete{
              font-size: 16px;
              margin-right: 10px;
            }
          }
        }
        .right_item_right{
          width: 80px;
          padding-right: 20px;
          display: flex;justify-content: flex-end;align-items: center;
        }
      }
      .right_item_footer{
        position: absolute;
        bottom: 2px;font-size: 12px;
        color: #999999;
      }
    }
  }
}
.largeScreenSetting_chart{
  .largeScreenSetting_container_main_right{
    width: 538px !important;
    .right_item_header{
      justify-content: unset;
      .right_item_header_left{
        padding-left: 15px !important;
        width: 160px;
      }
      .right_item_header_middle{
        flex: 1;
      }

    }
    .right_item_left_middle{
      flex: 1;

      .customization{
        display: flex;margin-right: 10px;
        .customization_name{
          //width: 100px;
          padding-right: 10px;
          display: flex;align-items: center;
        }
        .customization_value{
          flex: 1;
          //width: 150px;
          display: flex;align-items: center;
          ///deep/ .el-select__tags-text{
          //  max-width: 100px;
          //}
          /deep/ .el-tag--info{
            height: 18px;
          }
         /deep/ .el-input__inner{
           height: 25px !important;
           line-height: 25px !important;
         }
         /deep/ .el-input__suffix{
           height: 25px !important;
           line-height: 25px !important;
         }
        }
      }
    }
  }
}
</style>
